package com.ruoyi.manage.service.impl;

import java.util.ArrayList;
import java.util.List;

import com.ruoyi.common.annotation.DataScope;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.Ztree;
import com.ruoyi.common.exception.BusinessException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.manage.util.SmallareaUtil;
import com.ruoyi.system.domain.SysRole;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.manage.mapper.SmallareaMapper;
import com.ruoyi.manage.domain.Smallarea;
import com.ruoyi.manage.service.ISmallareaService;
import com.ruoyi.common.core.text.Convert;
import org.springframework.transaction.annotation.Transactional;

/**
 * 小区 服务层实现
 *
 * @author KEXUE
 * @date 2019-04-18
 */
@Service
public class SmallareaServiceImpl implements ISmallareaService {
    @Autowired
    private SmallareaMapper smallareaMapper;

    /**
     * 查询小区管理数据
     *
     * @param smallarea 小区信息
     * @return 小区信息集合
     */
    @Override
    @DataScope(tableAlias = "d")
    public List<Smallarea> selectSmallareaList(Smallarea smallarea)
    {
        return smallareaMapper.selectSmallareaList(smallarea);
    }

    /**
     * 查询小区管理树
     *
     * @param smallarea 小区信息
     * @return 所有小区信息
     */
    @Override
    @DataScope(tableAlias = "d")
    public List<Ztree> selectSmallareaTree(Smallarea smallarea)
    {
        List<Smallarea> smallareaList = smallareaMapper.selectSmallareaList(smallarea);
        List<Ztree> ztrees = initZtree(smallareaList);
        return ztrees;
    }

    /**
     * 根据角色ID查询小区（数据权限）
     *
     * @param role 角色对象
     * @return 小区列表（数据权限）
     */
    @Override
    public List<Ztree> roleSmallareaTreeData(SysRole role)
    {
        Long roleId = role.getRoleId();
        List<Ztree> ztrees = new ArrayList<Ztree>();
        List<Smallarea> smallareaList = selectSmallareaList(new Smallarea());
        if (StringUtils.isNotNull(roleId))
        {
            List<String> roleSmallareaList = smallareaMapper.selectRoleSmallareaTree(roleId);
            ztrees = initZtree(smallareaList, roleSmallareaList);
        }
        else
        {
            ztrees = initZtree(smallareaList);
        }
        return ztrees;
    }

    /**
     * 对象转小区树
     *
     * @param smallareaList 小区列表
     * @return 树结构列表
     */
    public List<Ztree> initZtree(List<Smallarea> smallareaList)
    {
        return initZtree(smallareaList, null);
    }

    /**
     * 对象转小区树
     *
     * @param smallareaList 小区列表
     * @param roleSmallareaList 角色已存在菜单列表
     * @return 树结构列表
     */
    public List<Ztree> initZtree(List<Smallarea> smallareaList, List<String> roleSmallareaList)
    {

        List<Ztree> ztrees = new ArrayList<Ztree>();
        boolean isCheck = StringUtils.isNotNull(roleSmallareaList);
        for (Smallarea smallarea : smallareaList)
        {
            if (UserConstants.SMALLAREA_NORMAL.equals(smallarea.getStatus()))
            {
                Ztree ztree = new Ztree();
                ztree.setId(smallarea.getSmallareaId());
                ztree.setpId(smallarea.getParentId());
                ztree.setName(smallarea.getSmallareaName());
                ztree.setTitle(smallarea.getSmallareaName());
                if (isCheck)
                {
                    ztree.setChecked(roleSmallareaList.contains(smallarea.getSmallareaId() + smallarea.getSmallareaName()));
                }
                ztrees.add(ztree);
            }
        }
        return ztrees;
    }

    /**
     * 查询小区人数
     *
     * @param parentId 小区ID
     * @return 结果
     */
    @Override
    public int selectSmallareaCount(Long parentId)
    {
        Smallarea smallarea = new Smallarea();
        smallarea.setParentId(parentId);
        return smallareaMapper.selectSmallareaCount(smallarea);
    }

    /**
     * 查询小区是否存在用户
     *
     * @param smallareaId 小区ID
     * @return 结果 true 存在 false 不存在
     */
    @Override
    public boolean checkSmallareaExistUser(Long smallareaId)
    {
        int result = smallareaMapper.checkSmallareaExistUser(smallareaId);
        return result > 0 ? true : false;
    }

    /**
     * 删除小区管理信息
     *
     * @param smallareaId 小区ID
     * @return 结果
     */
    @Override
    public int deleteSmallareaById(Long smallareaId)
    {
        return smallareaMapper.deleteSmallareaById(smallareaId);
    }

    /**
     * 新增保存小区信息
     *
     * @param smallarea 小区信息
     * @return 结果
     */
    @Override
    public int insertSmallarea(Smallarea smallarea)
    {
        Long parentId = smallarea.getParentId();
        if(parentId == null){
            throw new BusinessException("行政区划ID不能为空");
        }

        Smallarea info = smallareaMapper.selectSmallareaById(smallarea.getParentId());
        // 如果父节点不为"正常"状态,则不允许新增子节点
        if (!UserConstants.SMALLAREA_NORMAL.equals(info.getStatus()))
        {
            throw new BusinessException("区划停用，不允许新增");
        }

        // 获取当前小区ID
        Long smallareaId = SmallareaUtil.getSmallareaId(parentId);
        smallarea.setSmallareaId(smallareaId);
        // 固定小区排序为4     直接写死以防前端串改数据
        smallarea.setOrderNum("4");

        smallarea.setAncestors(info.getAncestors() + "," + parentId);
        return smallareaMapper.insertSmallarea(smallarea);
    }

    /**
     * 修改保存小区信息
     *
     * @param smallarea 小区信息
     * @return 结果
     */
    @Override
    @Transactional
    public int updateSmallarea(Smallarea smallarea)
    {
        Smallarea info = smallareaMapper.selectSmallareaById(smallarea.getParentId());
        if (StringUtils.isNotNull(info))
        {
            String ancestors = info.getAncestors() + "," + info.getSmallareaId();
            smallarea.setAncestors(ancestors);
            updateSmallareaChildren(smallarea.getSmallareaId(), ancestors);
        }
        // 固定小区排序为4     直接写死以防前端串改数据
        smallarea.setOrderNum("4");

        int result = smallareaMapper.updateSmallarea(smallarea);
        if (UserConstants.SMALLAREA_NORMAL.equals(smallarea.getStatus()))
        {
            // 如果该区划是启用状态，则启用该区划的所有上级区划
            updateParentSmallareaStatus(smallarea);
        }
        return result;
    }

    /**
     * 修改该小区的父级小区状态
     *
     * @param smallarea 当前小区
     */
    private void updateParentSmallareaStatus(Smallarea smallarea)
    {
        String updateBy = smallarea.getUpdateBy();
        smallarea = smallareaMapper.selectSmallareaById(smallarea.getSmallareaId());
        smallarea.setUpdateBy(updateBy);
        smallareaMapper.updateSmallareaStatus(smallarea);
    }

    /**
     * 修改子元素关系
     *
     * @param smallareaId 小区ID
     * @param ancestors 元素列表
     */
    public void updateSmallareaChildren(Long smallareaId, String ancestors)
    {
        Smallarea smallarea = new Smallarea();
        smallarea.setParentId(smallareaId);
        List<Smallarea> childrens = smallareaMapper.selectSmallareaList(smallarea);
        for (Smallarea children : childrens)
        {
            children.setAncestors(ancestors + "," + smallarea.getParentId());
        }
        if (childrens.size() > 0)
        {
            smallareaMapper.updateSmallareaChildren(childrens);
        }
    }

    /**
     * 根据小区ID查询信息
     *
     * @param smallareaId 小区ID
     * @return 小区信息
     */
    @Override
    public Smallarea selectSmallareaById(Long smallareaId)
    {
        return smallareaMapper.selectSmallareaById(smallareaId);
    }

    /**
     * 校验小区名称是否唯一
     *
     * @param smallarea 小区信息
     * @return 结果
     */
    @Override
    public String checkSmallareaNameUnique(Smallarea smallarea)
    {
        Long smallareaId = StringUtils.isNull(smallarea.getSmallareaId()) ? -1L : smallarea.getSmallareaId();
        Smallarea info = smallareaMapper.checkSmallareaNameUnique(smallarea.getSmallareaName(), smallarea.getParentId());
        if (StringUtils.isNotNull(info) && info.getSmallareaId().longValue() != smallareaId.longValue())
        {
            return UserConstants.SMALLAREA_NAME_NOT_UNIQUE;
        }
        return UserConstants.SMALLAREA_NAME_UNIQUE;
    }

    public void transforList() {
        List<Smallarea> list = smallareaMapper.selectSmallareaList(new Smallarea());
        List<Smallarea> newlist = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            Smallarea smallarea = list.get(i);
            Long parentId = smallarea.getParentId();
            if (parentId == 0) {
                smallarea.setAncestors("0,");
            } else {
                smallarea.setAncestors(tranforTree(new StringBuffer("0,"), parentId));
            }
            newlist.add(smallarea);
        }
        for (int i = 0; i < newlist.size(); i++) {
            smallareaMapper.updateSmallarea(newlist.get(i));
        }
    }

    public String tranforTree(StringBuffer ancestors, Long parentId) {
        if (parentId != 0) {
            Smallarea smallarea = smallareaMapper.selectSmallareaById(parentId);
            tranforTree(ancestors.append(parentId + ","), smallarea.getParentId());
        }
        return ancestors.toString();
    }
}
